#include "io.h"

#define SECTSIZE  512

// 等待磁盘空闲
static void ide_wait_idle(void)
{
    while((inb(0x1F7) & 0xC0) != 0x40);
}

// 读扇区数据
static void ide_sec_read(void *dst, u32 start)
{
    ide_wait_idle();

    // 发送读命令
    outb(0x1F2, 1);
    outb(0x1F3, start);
    outb(0x1F4, start >> 8);
    outb(0x1F5, start >> 16);
    outb(0x1F6, (start >> 24) | 0xE0);
    outb(0x1F7, 0x20);

    ide_wait_idle();

    // 读取数据
    insl(0x1F0, dst, SECTSIZE / 4);
}

// 读磁盘
void ide_read(u8* pa,  u32 off, u32 count)   
{                                             
    u8 *epa = pa + count;
    
    // 起始地址512字节对齐
    pa -= off % SECTSIZE;

    // 计算源数据所在扇区.
    off = (off / SECTSIZE) + 1;

    // 循环读取扇区
    for(; pa < epa; pa += SECTSIZE, off++)
        ide_sec_read(pa, off);
}